<?php

namespace app\api\service\alipay;

use app\admin\model\Member;
use app\admin\model\Orderitem;
use app\api\controller\Integralproduct;
use app\api\service\Detailed;
use app\common\DictConstant;
use app\lib\exception\OrderException;
use app\lib\exception\TokenException;

use think\Db;
use think\Exception;
use think\Log;

class OrderPay extends BasePay
{
    private $orderID;

    // 父类有 __construct
    /*function __construct($orderID)
    {
        if(!$orderID){
            throw new Exception('订单号不能为空');
        }
        $this->orderID = $orderID;
    }*/

    // 调用支付宝支付
    public function pay($orderID)
    {
        if(!$orderID){
            throw new Exception('订单号不能为空');
        }
        $this->orderID = $orderID;

        //订单号可能根本就不存在
        //订单号确实是存在的，但是，订单号和当前用户是不匹配的
        //订单有可能已经被支付过
        //发起支付之前再进行库存量检测
        $this->checkOrderValid();
        $order = \app\admin\model\Order::get($this->orderID);
        $Orderitem = Orderitem::where('order_id',$order->id)->find();

        $trade_no = $this->orderID;
        $total_amount = $order['total'];
        $body = $Orderitem->product_name;
        $subject = $Orderitem->product_name;
        $notify_url = config('alipay.pay_back_url');
        $result = $this->run($body, $subject, $trade_no, $total_amount, $notify_url);

        return show(config('status.SUCCESS_STATUS'), 'ok', $result);
    }

    //对订单号进行检测
    private function checkOrderValid(){
        $order = \app\common\model\Order::where('id','=',$this->orderID)->find();
        if(!$order){
            throw new OrderException();
        }
//        if(!Token::isValidOperate($order->member_id)){
//            throw new TokenException([
//                'msg' => '订单与用户不匹配',
//                'errorCode' => 10003
//            ]);
//        }
        if($order->status != DictConstant::OrderPendingPayment){
            throw new OrderException([
                'msg' => '该订单已经支付过了',
                'errorCode' => 80003,
                'code' => 400
            ]);
        }
        return true;
    }
}